package com.test.many.very_much.controller;

import com.test.many.very_much.dto.AccessTokenDTO;
import com.test.many.very_much.dto.GiteeUser;
import com.test.many.very_much.dto.GithubUser;
import com.test.many.very_much.provider.GiteeProvider;
import com.test.many.very_much.provider.GithubProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* @Description:    gitee授权页
* @Author:         Joe
* @CreateDate:     2020/4/2 15:40
*/
@Controller
@Slf4j
public class AuthorizeController {
/*
* 1.应用通过 浏览器 或 Webview 将用户引导到码云三方认证页面上（ GET请求 ）
*https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code
* 2.用户对应用进行授权
*https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&scope=user_info%20projects%20pull_requests
* 3.码云认证服务器通过回调地址{redirect_uri}将 用户授权码 传递给 应用服务器 或者直接在 Webview 中跳转到携带 用户授权码的回调地址上，Webview 直接获取code即可（{redirect_uri}?code=abc&state=xyz)
* 4.应用服务器 或 Webview 使用 access_token API 向 码云认证服务器发送post请求传入 用户授权码 以及 回调地址（ POST请求 ）
*https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
* */
    @Value("${gitee.client.id}")
    private String giteeClientId;
    @Value("${gitee.client.secret}")
    private String giteeClientSecret;
    @Value("${gitee.redirect.uri}")
    private String giteeRedirectUri;

    @Autowired
    private GiteeProvider giteeProvider;


    @Value("${github.client.id}")
    private String githubClientId;
    @Value("${github.client.secret}")
    private String githubClientSecret;
    @Value("${github.redirect.uri}")
    private String githubRedirectUri;
    @Autowired
    private GithubProvider githubProvider;


    /**
     * 登录回调处理
     * @param code
     * @param response
     * @return
     */
    @RequestMapping(value = "/tologincallback",method = RequestMethod.GET)
    public String callback(@RequestParam(name = "code")String code,
                           HttpServletResponse response,HttpServletRequest request){
        //1.拼接access_token API必要参数
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(giteeClientId);
        accessTokenDTO.setClient_secret(giteeClientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(giteeRedirectUri);
        accessTokenDTO.setGrant_type("authorization_code");
        //2.获取access_token
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
        //3.获取用户数据
        GiteeUser gitUser = giteeProvider.getUser(accessToken);
        if (gitUser!=null && gitUser.getId()!=null){
            log.info("用户id:{}"+gitUser.getId()+",用户昵称:{}"+gitUser.getName()+"用户自我介绍:{}"+gitUser.getBio());
            //4.可将此处用户数据进行数据库保存……在此省略(可将用户ID转token存入cookie，拦截可通过cookie在数据库查询用户信息)
            //5.登录成功，可将此处用户数据写入cookie及Session
            String token = gitUser.getId().toString();
            Cookie cookie = new Cookie("token",token);
            response.addCookie(cookie);
            HttpSession session =request.getSession();
            session.setAttribute("user",gitUser);
            System.out.println("授权完成");
            //6.重定向到首页
            return "redirect:/";

        }else {
            log.error("callback get gitee error,{}"+gitUser);
            //登录失败，重新登录
            System.out.println("授权失败");
            return "redirect:/";
        }

    }

    /**
     * 登录回调处理
     * @param code
     * @param response
     * @return
     */
    @RequestMapping(value = "/tologincallbacks",method = RequestMethod.GET)
    public String callbacks(@RequestParam(name = "code")String code,@RequestParam(name = "state")String state,
                           HttpServletResponse response,HttpServletRequest request){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(githubClientId);
        accessTokenDTO.setClient_secret(githubClientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(githubRedirectUri);
        accessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        if (githubUser!=null && githubUser.getId()!=null){
            log.info("用户id:{}"+githubUser.getId()+",用户昵称:{}"+ githubUser.getLogin()+"用户头像:{}"+githubUser.getAvatar_url());
            String token = githubUser.getId().toString();
            Cookie cookie = new Cookie("token",token);
            response.addCookie(cookie);
            HttpSession session =request.getSession();
            session.setAttribute("userh",githubUser);
            System.out.println("授权完成");
            //6.重定向到首页
            return "redirect:/";

        }else {
            log.error("callback get github error,{}"+githubUser);
            //登录失败，重新登录
            System.out.println("授权失败");
            return "redirect:/";
        }

    }


}
